package org.neuedu.servlet;

import org.neuedu.bean.Article;
import org.neuedu.bean.User;
import org.neuedu.service.ArticleService;
import org.neuedu.service.ArticleServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "ArticleAddServlet",urlPatterns = "/article/add")
public class ArticleAddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取 class,title,content,experience,uid
        // 从session中获取登录者id
        // 准备dao和service dao : 1.插入文章信息；2.修改user表中的飞吻；3.更新session中对象的飞吻
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        Integer cid = Integer.valueOf(request.getParameter("class"));
        Integer paykiss = Integer.valueOf(request.getParameter("experience"));
        HttpSession session = request.getSession();
        User fly_user = (User)session.getAttribute("fly_user");



        Integer uid = fly_user.getId();

        // service
        Article article = new Article();
        article.setCid(cid);
        article.setUid(uid);
        article.setContent(content);
        article.setPayKiss(paykiss);
        article.setTitle(title);
        ArticleService service = new ArticleServiceImpl();


        int i = service.articlePublish(article);
        if(i != 0){
           fly_user.setKissNum(fly_user.getKissNum()-paykiss);


            // 添加成功

            response.sendRedirect(request.getContextPath()+"/forward/index");
        }else{
            //失败
            request.setAttribute("publishFailMsg","发布失败");
            request.getRequestDispatcher("/forward/add").forward(request,response);
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
